package com.song.tools.songtest.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.song.tools.core.beans.LogId;
import com.song.tools.core.exception.BusinessException;
import com.song.tools.core.exception.ExceptionCodeEnum;
import com.song.tools.core.util.UserUtil;
import com.song.tools.songtest.beans.response.SysUserQueryResponse;
import com.song.tools.songtest.beans.vo.UserVO;
import com.song.tools.songtest.config.WithoutLogin;
import com.song.tools.songtest.constants.SexEnum;
import com.song.tools.songtest.constants.StatusEnum;
import com.song.tools.songtest.constants.StringPool;
import com.song.tools.songtest.service.SysUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.webmvc.api.MultipleOpenApiResource;
import org.springdoc.webmvc.ui.SwaggerConfigResource;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * 请求响应拦截器
 *
 * @version v1.0
 * @author: backend-manage
 * @date: 2024年03月20日 23时31分
 */
@Slf4j
public class RequestHolderHandlerInterceptor implements HandlerInterceptor {

    @Resource
    private SysUserService sysUserService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod action) {
            WithoutLogin withoutLogin = action.getMethodAnnotation(WithoutLogin.class);
            if (withoutLogin != null) {
                return true;
            }
        } else {
            // 不是一个请求方法
            return true;
        }

        if (action.getBean() instanceof SwaggerConfigResource || action.getBean() instanceof MultipleOpenApiResource) {
            return true;
        }

        UserUtil.remove();
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        // 加上校验放行
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return true;
        }

        // 设置用户信息，从请求头中获取
        setUserInfo(request);
        setLogId(request);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.remove();
    }

    private void setUserInfo(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader(StringPool.SA_TOKEN);
        // 从请求头中获取角色
        String roleId = request.getHeader(StringPool.ROLE_ID);

        if (StrUtil.isBlank(token) || StrUtil.isBlank(roleId)) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (StringPool.SA_TOKEN.equals(cookie.getName()) && StrUtil.isBlank(token)) {
                        token = cookie.getValue();
                        continue;
                    }
                    if (StringPool.ROLE_ID.equals(cookie.getName()) && StrUtil.isBlank(roleId)) {
                        roleId = cookie.getValue();
                    }
                }
            }
        }

        if (StrUtil.isNotBlank(token) && token.startsWith(StringPool.TOKEN_PREFIX)) {
            token = token.replaceFirst(StringPool.TOKEN_PREFIX, StringPool.EMPTY_STR);
        }

        // 用户登录拦截
        Object loginId = StpUtil.getLoginIdByToken(token);
        if (Objects.isNull(loginId)) {
            throw new BusinessException(ExceptionCodeEnum.USER_NOT_LOGIN);
        }

        // todo 如果接入了redis，先查redis，如果有数据直接返回

        // 从数据库查询用户信息
        UserVO userVO = getUserInfoFromDb(Long.valueOf(loginId.toString()));
        userVO.setToken(token);
        if (StrUtil.isNotBlank(roleId)) {
            userVO.setRoleId(Long.valueOf(roleId));
        }
        UserUtil.set(userVO);
    }

    private void setLogId(HttpServletRequest request) {
        // 从请求头中获取logId
        String logId = request.getHeader(StringPool.LOG_ID);
        if (StringUtils.hasLength(logId)) {
            LogId.put(logId);
            return;
        }
        LogId.put(StrUtil.uuid());
    }

    /**
     * 从数据库中获取用户信息
     *
     * @param id 用户id
     * @return 用户信息
     */
    private UserVO getUserInfoFromDb(Long id) {
        // 查用户信息
        SysUserQueryResponse sysUser = sysUserService.getOneByUniqueKey(id, "id");
        UserVO userVO = new UserVO();
        userVO.setId(sysUser.getId());
        userVO.setUsername(sysUser.getUsername());
        userVO.setLoginAccount(sysUser.getLoginAccount());
        userVO.setEmail(sysUser.getEmail());
        userVO.setPhone(sysUser.getPhone());
        userVO.setProfilePhoto(sysUser.getProfilePhoto());
        userVO.setSex(SexEnum.of(sysUser.getSex()));
        userVO.setStatus(StatusEnum.of(sysUser.getStatus()));
        userVO.setAge(sysUser.getAge());
        userVO.setBirthday(sysUser.getBirthday());
        userVO.setRemark(sysUser.getRemark());
        userVO.setCreateUsername(sysUser.getCreateUsername());
        return userVO;
    }
}
